﻿using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Forms;
using System.Diagnostics.CodeAnalysis;
using System.Linq.Expressions;

namespace Cyss.TaskControl.Components
{

    public interface IRealTableColumn
    {

        string FileName { get; }

        string? GetDisplayName();

        /// <summary>
        /// 获得/设置 显示模板
        /// </summary>
        RenderFragment<object>? Template { get; set; }
    }

    public class RealTableColumn<TItem, TType> : ComponentBase, IRealTableColumn
    {
        /// <summary>
        /// 获得/设置 数据绑定字段值
        /// </summary>
        [Parameter]
        [MaybeNull]
        public TType Field { get; set; }


        [Parameter]
        public EventCallback<TType> FieldChanged { get; set; }

        /// <summary>
        /// 获得/设置 ValueExpression 表达式
        /// </summary>
        [Parameter]
        public Expression<Func<TType>>? FieldExpression { get; set; }


        /// <summary>
        /// 获得/设置 表头显示文字
        /// </summary>
        [Parameter]
        public string? Text { get; set; }

        /// <summary>
        /// 获得/设置 绑定列类型
        /// </summary>
        [NotNull]
        public Type? PropertyType { get; set; }
        public string FileName
        {
            get
            {
                return _fieldIdentifier.Value.FieldName;
            }
        }


        /// <summary>
        /// 获得/设置 Table 实例
        /// </summary>
        [CascadingParameter]
        protected IRealTable? Table { get; set; }

        [Parameter]
        public RenderFragment<RealTableColumnContext<TItem, TType>>? Template { get; set; }

        /// <summary>
        /// 内部使用负责把 object 类型的绑定数据值转化为泛型数据传递给前端
        /// </summary>
        RenderFragment<object>? IRealTableColumn.Template
        {
            get => Template == null ? null : new RenderFragment<object>(context => builder =>
            {
                // 此处 context 为行数据
                var fieldName = this.FileName;
                var value = (TType)Convert.ChangeType(context.GetType().GetProperty(this.FileName).GetValue(context), typeof(TType));
                builder.AddContent(0, Template.Invoke(new RealTableColumnContext<TItem, TType>((TItem)context, value)));
            });
            set
            {

            }
        }


        private FieldIdentifier? _fieldIdentifier;


        /// <summary>
        /// 组件初始化方法
        /// </summary>
        protected override void OnInitialized()
        {

            Table?.Columns.Add(this);
            // 获取模型属性定义类型
            PropertyType = typeof(TType);

            if (FieldExpression != null)
            {
                _fieldIdentifier = FieldIdentifier.Create(FieldExpression);
            }
        }

        public string GetDisplayName()
        {
            if (string.IsNullOrWhiteSpace(Text))
            {
                return FileName;
            }
            return Text;
        }
    }
}
